<template>
  <div style="height: 100%;background-color:white ;padding: 10px">
    <div>
      <div style="display: inline-block">
        <el-button icon="el-icon-back" size="small" type="text" @click="goBack">返回</el-button>
      </div>
      <div style="display: inline-block">|</div>
      <div style="display: inline-block;">
        <div style="padding-bottom: 15px;margin-left:10px">
          <span style=" font-family: 'Microsoft YaHei',serif;display: inline-block">详情</span>
        </div>
      </div>
    </div>
    <el-row>
      <el-col :span="4" style="text-align: left">
        <el-button v-if="this.radioStatus==='undistributed'&&this.type!=='all'" size="small" type="success"
                   @click="multiEdit('all')">一键分配
        </el-button>
        <el-button v-if="this.radioStatus==='undistributed'&&this.type!=='all'" size="small" type="success"
                   @click="multiEdit('multi')">
          批量分配
        </el-button>
        <div style="display: inline-block">
          <span></span>
        </div>
      </el-col>
      <el-col :span="8" style="text-align: right">
        <el-radio-group v-model="radioStatus" size="small" style="margin-left: 130px" @change="valueChange()">
          <el-radio-button label="undistributed">未分配</el-radio-button>
          <el-radio-button label="distribution">已分配</el-radio-button>
          <el-radio-button label="fail">失败</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="12" style="right: auto">
        <div v-if="this.radioStatus=='distribution'||this.radioStatus=='undistributed'">
          <div style="width: 430px; float: right">
            <el-input v-model="name" placeholder="请输入知识名称" size="small" @keyup.enter.native="getActivityItemTableData">
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button slot="append" :icon="appendIcon" @click="switchAppend"></el-button>
            </el-input>
          </div>
          <div v-if="showAdvance" id="advance" style="padding: 10px; float: right">
            <div>
              <div style="width: 100px;text-align:right; display: inline-block">
                <span>稿件名称</span>
              </div>
              <div style="display: inline-block">
                <el-input v-model="manuscriptName" placeholder="请输入稿件名称" size="small"
                          style="width: 300px;margin-top: 10px"></el-input>
              </div>
            </div>
            <div v-if="this.radioStatus=='distribution'">
              <div style="width: 100px;text-align:right; display: inline-block">
                <span>任务名称</span>
              </div>
              <div style="display: inline-block">
                <el-input v-model="takName" placeholder="请输入任务名称" size="small"
                          style="width: 300px;margin-top: 10px"></el-input>
              </div>
            </div>
            <div style="width: 100px;text-align:right; display: inline-block;margin-top: 10px">
              <span>知识库</span>
            </div>
            <div style="display: inline-block">
              <el-select v-model="selectedLib" clearable filterable placeholder="请选择所属知识库" size="small"
                         style="width: 300px">
                <el-option v-for="item in $store.state.knowledgeLibList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div style="margin-top: 60px; right: 10px;">
              <el-row>
                <el-col :offset="7" :span="9">
                  <div style="margin-left: 90px;height: 32px; width: 88px;">
                    <el-button size="small" v-on:click="advanceCancel">取 消</el-button>
                  </div>
                </el-col>
                <el-col :offset="0.8" :span="2">
                  <div div style="margin-left: 5px;height: 32px; width: 88px;">
                    <el-button size="small" type="success" v-on:click="replacement">重 置</el-button>
                  </div>
                </el-col>
                <el-col :offset="2" :span="2">
                  <div div style="margin-left: 5px;height: 32px; width: 88px;">
                    <el-button size="small" type="success" v-on:click="advanceConfirm">确 定</el-button>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <div>
        <el-table :data="tableData" :height="tableHeight" border stripe style="width: 100%;margin-top: 10px"
                  @selection-change="handleSelectionChange">
          <el-table-column
            v-model="multipleSelection"
            type="selection"
            width="55">
          </el-table-column>
          l
          <el-table-column v-if="this.radioStatus=='distribution'||this.radioStatus=='undistributed'" label="知识名称"
                           min-width="300" prop="knowledgeName">
            <template slot-scope="scope">
              <span v-html="scope.row.knowledgeName"></span>
            </template>
          </el-table-column>
          <el-table-column label="稿件名称" min-width="100" prop="manuscriptName"></el-table-column>
          <el-table-column label="所属知识库" min-width="100" prop="knowledgeLibName"></el-table-column>
          <el-table-column label="状态" min-width="150" prop="status">
            <template slot-scope="scope">
              <span v-if="scope.row.status==0">未分配</span>
              <span v-if="scope.row.status==1">已分配</span>
              <span v-if="scope.row.status==2">解析失败
              <el-popover
                :content="scope.row.failureReason"
                trigger="hover">
                    <el-button slot="reference" style="margin-left: 10px;" type="text"><span
                      style="color: red">详情</span></el-button>
                  </el-popover>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" min-width="160"
                           prop="updatedTime"></el-table-column>
          <el-table-column v-if="this.radioStatus=='distribution'" label="任务名称" min-width="150"
                           prop="taskName"></el-table-column>
          <el-table-column v-if="type==='single'" label="操作" min-width="200">
            <template slot-scope="scope">
                <span><el-link v-if="scope.row.status==0" type="success"
                               @click.prevent="edit(scope.row)">分配任务</el-link></span>
              <span><el-link v-if="scope.row.status==0||scope.row.status==1" type="success"
                             @click.prevent="detailById(scope.row.knowledgeId)">知识详情</el-link></span>
              <span><el-link type="success"
                             @click.prevent="download(scope.row.path)">稿件下载</el-link></span>

            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-row>
      <div style="margin-top: 10px">
        <el-pagination
          v-if="multiplePages"
          :page-size="pageSize"
          :page-sizes="[5, 10, 15, 20, 50, 100]"
          :total="totalNum"
          background
          layout="total, sizes, prev, pager, next, jumper"
          style="text-align: right;"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"></el-pagination>
      </div>
    </el-row>
    <el-dialog :visible.sync="selectTaskDialogVisible" title="新建子任务" width="500px">
      <el-row>
        <el-col :span="6">
          <span class="label">选择任务<em style="color: red">*</em></span>
        </el-col>
        <el-col :span="18">
          <el-select v-model="selectedTaskId" filterable placeholder="请选择"
                     style="width: 100%">
            <el-option
              v-for="(item,index) in taskList"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="6">
          <span class="label">备注</span>
        </el-col>
        <el-col :span="18">
          <el-input v-model.trim="taskItemRemark"/>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSelectTaskDialog">取 消</el-button>
        <el-button type="primary" @click="insertTaskItem">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ActivityDetail",

  data() {
    return {
      tableData: [],
      multiplePages: true,
      appendIcon: "el-icon-caret-bottom",
      noData: true,
      totalNum: 0,
      showAdvance: false,
      currentPage: 0, // 第几页
      pageSize: 10, // 每页显示的数据个数
      name: '',
      takName: '',
      selectedLib: '',
      radioStatus: 'undistributed',
      options: [],
      tableHeight: '',
      activityId: '',
      manuscriptName: '',
      taskItemRemark: '',
      selectedTaskId: '',
      selectTaskDialogVisible: false,
      taskList: [],
      knowledgeLibId: '',
      activityItem: {},
      editType: 'single',
      multipleSelection: [],
      type: ''
    }
  },
  methods: {
    insertTaskItem() {
      if (!this.selectedTaskId) {
        this.$message.warning("请选择挂载任务")
        return
      }
      // 单条数据修订;
      if (this.editType === 'single') {

        let param = new URLSearchParams();
        param.append("taskItem", JSON.stringify({
          task_id: this.selectedTaskId,
          name: this.activityItem.knowledgeName,
          knowledge_id: this.activityItem.knowledgeId,
          type: 0,
          remark: this.taskItemRemark,
        }))
        param.append("activityItem", JSON.stringify(this.activityItem))
        this.axios.post('/pmph/action/task/taskItemSave', param)
          .then(() => {
            this.closeSelectTaskDialog()
            this.getActivityItemTableData()
          })
      }
      // 一键修订;
      else {
        let param = new URLSearchParams();
        param.append("editType", this.editType)
        param.append("selectedActivityIds", JSON.stringify(this.multipleSelection.map(item => item.id)))
        param.append("taskId", this.selectedTaskId)
        param.append("remark", this.taskItemRemark)
        param.append('searchParams', JSON.stringify({
          id: this.activityId,
          name: this.name,
          manuscriptName: this.manuscriptName,
          currentPage: this.currentPage,
          knowledgeLibId: this.selectedLib,
        }));
        this.axios.post('/pmph/action/activity/saveTaskItemList', param)
          .then(() => {
            this.closeSelectTaskDialog()
            this.getActivityItemTableData()
          })
      }
    },

    closeSelectTaskDialog() {
      this.selectTaskDialogVisible = false
      this.taskList = []
      this.taskItemRemark = ''
      this.selectedTaskId = ''
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    switchAppend: function () {
      if (this.showAdvance) {
        this.showAdvance = false;
        this.appendIcon = "el-icon-caret-bottom";
      } else {
        this.showAdvance = true;
        this.appendIcon = "el-icon-caret-top";
      }
    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.getActivityItemTableData();
    },
    handleSizeChange(value) {
      this.pageSize = value
      this.getActivityItemTableData()
    },
    advanceCancel() {
      this.showAdvance = false;
    },
    goBack() {
      this.$router.go("-1")
    },
    replacement: function () {
      this.name = ''
      this.selectedLib = ''
      this.created_by = ''
      this.manuscriptName = ''
    },
    advanceConfirm() {
      this.getActivityItemTableData()
      this.showAdvance = false;
    },
    closeNewDialog() {
      this.dialogVisible = false
    },
    download(path) {
      window.location.href = path
    },
    detailById: function (id) {
      this.$store.commit('setKnowledgeDetailId', id)
      this.$store.commit('setKnowledgeDetailStatus', 'unpublished')
      this.$store.commit('showKnowledgeDetail')
    },
    edit: async function (row) {
      this.editType = 'single'
      this.activityItem = row
      let checkFlag = false
      // 查询本知识是否已和正在进行中的子任务关联
      await this.axios.get('/pmph/action/task/selectTaskItemInProcessByKnowledgeId', {
        params: {
          knowledgeId: row.knowledgeId,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.$message.warning("当前知识分配任务, 请勿重复分配")
        } else {
          checkFlag = true
        }
      })
      if (checkFlag) {
        // 查询当前知识库关联正在进行中的任务, 供用户选择
        this.axios.get('/pmph/action/task/selectTaskInProcessByKnowledgeLibId', {
          params: {
            knowledgeLibId: row.knowledgeLibId,
          }
        }).then((response) => {
          if (response.data.length > 0) {
            this.taskList = response.data
            this.selectTaskDialogVisible = true
          } else {
            this.$message.warning("您还没有符合条件的任务可以进行分配!")
          }
        })
      }
    },
    multiEdit: function (editType) {
      let knowledgeLibId = '';
      if (this.knowledgeLibId === '0001AA100000000WD6YX') {
        if (!this.selectedLib) {
          this.$message.warning("此稿件隶属两个知识库，请按知识库搜索后再分配")
          return
        } else {
          knowledgeLibId = this.selectedLib;
        }
      } else {
        knowledgeLibId = this.knowledgeLibId;

      }
      this.editType = editType
      if (editType === 'multi' && this.multipleSelection.length === 0) {
        this.$message.warning("请选择修订的知识!")
        return
      }
      // 查询当前知识库关联正在进行中的任务, 供用户选择
      this.axios.get('/pmph/action/task/selectTaskInProcessByKnowledgeLibId', {
        params: {
          knowledgeLibId: knowledgeLibId,
        }
      }).then((response) => {
        if (response.data.length > 0) {
          this.taskList = response.data
          this.selectTaskDialogVisible = true
        } else {
          this.$message.warning("当前知识库没有正在进行中的任务, 请先新建任务!")
        }
      })
    },
    valueChange: function () {
      this.getActivityItemTableData()
    },
    getActivityItemTableData() {
      this.axios.get("/pmph/action/activity/selectActivityItemTableData", {
        params: {
          id: this.activityId,
          name: this.name,
          manuscriptName: this.manuscriptName,
          currentPage: this.currentPage,
          knowledgeLibId: this.selectedLib,
          pageSize: this.pageSize,
          radioStatus: this.radioStatus,
        }
      }).then((response) => {
        this.totalNum = response.data.total;
        this.tableData = response.data.records
        console.log(response)
      })
    }
  },
  created() {
    this.activityId = this.$route.query.id
    this.type = this.$route.query.detailType
    this.knowledgeLibId = this.$route.query.knowledgeLibId
    console.log(this.type)
    this.tableHeight = CONST.WORKSPACE_HEIGHT - 150;
    this.getActivityItemTableData()
  }
}
</script>

<style scoped>

</style>
